/*
 * Copyright 2018-2019 KunMinX
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain menu_text_color copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.wanchuang.hepos.ui.page.home;

import android.Manifest;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.ContentObserver;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.lifecycle.ViewModelProviders;

import com.wanchuang.architecture.utils.GPSUtils;
import com.wanchuang.hepos.R;
import com.wanchuang.hepos.bridge.request.HomeRequestViewModel;
import com.wanchuang.hepos.bridge.state.home.QrViewModel;
import com.wanchuang.hepos.databinding.FragmentQrBinding;
import com.wanchuang.hepos.help.DialogUtils;
import com.wanchuang.hepos.help.GlideHelper;
import com.wanchuang.hepos.help.PermissionHelper;
import com.wanchuang.hepos.proto.Scan;
import com.wanchuang.hepos.ui.base.BaseFragment;
import com.wanchuang.hepos.ui.utils.GPS_Interface;
import com.wanchuang.hepos.ui.utils.GPS_Presenter;
import com.wanchuang.hepos.ui.zxing.activity.CaptureActivity;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import static android.content.Context.LOCATION_SERVICE;


/**
 * Create by KunMinX at 19/10/29
 */
public class QrFragment extends BaseFragment implements GPS_Interface {

    private FragmentQrBinding mBinding;

    private QrViewModel mViewModel;

    private HomeRequestViewModel mRequestViewModel;

    private Scan.scan_basis mBasis;

    private List<ImageView> ImageList = new ArrayList<>();

    private Location mLocation;

    private GPS_Presenter gps_presenter;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mViewModel = ViewModelProviders.of(this).get(QrViewModel.class);
        mRequestViewModel = ViewModelProviders.of(this).get(HomeRequestViewModel.class);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_qr, container, false);
        mBinding = FragmentQrBinding.bind(view);
        mBinding.setClick(new ClickProxy());
        mBinding.setVm(mViewModel);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        gps_presenter = new GPS_Presenter(getActivity(), this);
        mRequestViewModel.getErrorString().observe(this, error -> {
            hideProgress();
            showShortToast(error);
        });

        mRequestViewModel.getBank().observe(this, bank -> {
            hideProgress();
            mViewModel.bean.set(bank);
            mViewModel.name.set(bank.getBankName() + "(" + bank.getBankCard().substring(bank.getBankCard().length() - 4) + ")");
        });


        mRequestViewModel.getScanType().observe(this, scan_type -> {
            hideProgress();
            for (Scan.scan_basis item : scan_type.getListList()) {
                View tempView = View.inflate(mActivity, R.layout.item_money_item, null);
                TextView tvTitle = tempView.findViewById(R.id.tv_name);
                tvTitle.setText(item.getName());
                ImageView llBg = tempView.findViewById(R.id.iv_bg);
                ImageView ivSelect = tempView.findViewById(R.id.iv_select);
                ImageList.add(ivSelect);
                GlideHelper.INSTANCE.loadFitXYImage(llBg, item.getLogo());
                RelativeLayout rvMoney = tempView.findViewById(R.id.rv_money_item);
                rvMoney.setOnClickListener(v -> {
                            mBasis = item;
                            for (ImageView iv : ImageList) {
                                iv.setImageResource(R.mipmap.icon_point_unselect);
                            }
                            ivSelect.setImageResource(R.mipmap.icon_point_select);
                        }
                );
                mBinding.llQr.addView(tempView);
            }
        });
        mRequestViewModel.getScanTypeInfo();
        mRequestViewModel.get_bank();
        getLastKnownLocation();
    }


    private void getLastKnownLocation() {
        List<String> permissions = new ArrayList<>();
        permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
        permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);
        permissions.add(Manifest.permission.CAMERA);
        PermissionHelper.getInstance().getPermissionGroup(mActivity, new PermissionHelper.PermissionCallBack() {
            @Override
            public void onSuccess() {
                // 获取手机品牌
                LocationManager mLocationManager = (LocationManager) mActivity.getSystemService(LOCATION_SERVICE);
                boolean gpsEnabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
                if (gpsEnabled) {
                    showProgress();
                    if (ActivityCompat.checkSelfPermission(mActivity, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mActivity, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                        return;
                    }
                    mLocationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,      //GPS定位提供者
                            500,       //更新数据时间为1秒
                            1,      //位置间隔为1米
                            //位置监听器
                            new LocationListener() {  //GPS定位信息发生改变时触发，用于更新位置信息

                                @Override
                                public void onLocationChanged(Location location) {
                                    //GPS信息发生改变时，更新位置
                                    locationUpdates(location);
                                }

                                @Override
                                //位置状态发生改变时触发
                                public void onStatusChanged(String provider, int status, Bundle extras) {
                                }

                                @Override
                                //定位提供者启动时触发
                                public void onProviderEnabled(String provider) {
                                }

                                @Override
                                //定位提供者关闭时触发
                                public void onProviderDisabled(String provider) {
                                }
                            });
                    //从GPS获取最新的定位信息
                    Location location = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    locationUpdates(location);    //将最新的定位信息传递给创建的locationUpdates()方法中
                } else {
                    DialogUtils.showHitDialog(mActivity,"提示","定位失败,请打开GPS服务后重试");
                }
            }

            @Override
            public void onFail() {
                Toast.makeText(mActivity, "获取权限失败", Toast.LENGTH_SHORT).show();
            }
        }, permissions);


    }

    @Override
    public void gpsSwitchState(boolean gpsOpen) {
        if (gpsOpen) {
            getLastKnownLocation();
        }
    }


    public class ClickProxy {

        public void back() {
            nav().navigateUp();
        }

        public void submit() {
            String money = mViewModel.money.get();
            if (TextUtils.isEmpty(money)) {
                showShortToast("请先输入金额");
                return;
            }
            if (mBasis == null) {
                showShortToast("请先选中扫码类型");
                return;
            }
            if (mLocation == null) {
                showShortToast("获取定位失败,请打开GPS定位服务");
                return;
            }
            String brand = android.os.Build.BRAND;
            String edition = Build.MODEL;
            Intent intent = new Intent(mActivity, CaptureActivity.class);
            intent.putExtra("title", mBasis.getName());
            intent.putExtra("bg_color", "#" + mBasis.getColour());
            intent.putExtra("brand", brand);
            intent.putExtra("edition", edition);
            intent.putExtra("amount", mViewModel.money.get());
            intent.putExtra("type", mBasis.getType());
            intent.putExtra("station", mLocation.getLatitude() + "," + mLocation.getLongitude());
            startActivity(intent);
        }
    }


    public void locationUpdates(Location location) {  //获取指定的查询信息
        //如果location不为空时
        if (location != null) {
            hideProgress();
            StringBuilder stringBuilder = new StringBuilder();        //使用StringBuilder保存数据
            //获取经度、纬度、等属性值
            stringBuilder.append("您的位置信息：\n");
            stringBuilder.append("经度：");
            stringBuilder.append(location.getLongitude());
            stringBuilder.append("\n纬度：");
            stringBuilder.append(location.getLatitude());
            mLocation = location;
            List<Address> address =    getAddress(location);
           Log.e("地址",address.toString());
        }
    }


    private List<Address> getAddress(Location location) {
        List<Address> result = null;
        try {
            if (location != null) {
                Geocoder gc = new Geocoder(mActivity, Locale.getDefault());
                result = gc.getFromLocation(location.getLatitude(),
                        location.getLongitude(), 1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        //释放资源
        if (gps_presenter != null) {
            gps_presenter.onDestroy();
        }
    }
}


